package com.vfa.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import com.vfa.vocaburay.R;
import com.vfa.vocaburay.TestNetworkConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ExportData extends Activity{
	
	private static final int DIALOG_EXPORT = 0;
	private static final int DIALOG_AUTHO = 1;
	private static final int DIALOG_RESULT_AUTHO = 2;
	private static final int DIALOG_WAITTING = 3;
	
	public static WordData wordData;
	private Button btnExport;
	private String languageExport;
	private String[] arrlanguageExport;
	
	private ArrayList<String> arr;
	private ArrayList<String> arrlangcheck;
	private LinearLayout lllistlang;
	CheckBox checkbox, checkboxall;
	
	private CheckBox checkbox_Sync;
	
	ArrayList<String> arrlistlanguage;
	private int flag=0;
	
	String path;

	ArrayList<String> data;
	
	private TextView viewpath, showstatus;
	private EditText et_Enterfilename;
	String filename;
	String filepath;
	private ProgressBar progress;
	private int myprogress=0;
	private String dialogmessage;
	private Boolean isCheksync;
	
	SyncDocs syncDocs;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exportdata_activity);
		wordData = new WordData(getApplicationContext());
		data = new ArrayList<String>();
		
		lllistlang = (LinearLayout)findViewById(R.id.linearLayout_listLanguage);
		btnExport = (Button)findViewById(R.id.btn_ExportWord);
		viewpath = (TextView)findViewById(R.id.textView_filepathtoexport);
		showstatus = (TextView)findViewById(R.id.textView_showstatusexport);
		et_Enterfilename = (EditText)findViewById(R.id.editText_enterfilename);
		progress = (ProgressBar)findViewById(R.id.progressBar_export);
		
		checkbox_Sync = (CheckBox)findViewById(R.id.checkBox_Sync_Question_Word);
		syncDocs = new SyncDocs(this);
		
		
		String projectname = "/android/data/com.vfa.vocabulary/";
		
		path = Environment.getExternalStorageDirectory() + projectname;
		
		viewpath.setText(path);
		et_Enterfilename.setText("Wordbackup");
		
		arrlangcheck = new ArrayList<String>();
		
		arrlistlanguage = wordData.getAllLanguage();
		
		checkboxall = new CheckBox(this);
		checkboxall.setText("All");
		lllistlang.addView(checkboxall);
		
		for (int i = 0; i<arrlistlanguage.size(); i++){
			checkbox = new CheckBox(this);
			checkbox.setText(arrlistlanguage.get(i));
			checkbox.setId(i+1);			
			checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(isChecked)
					{
						arrlangcheck.add(buttonView.getText().toString());
						flag++;
						System.out.println("flag =   " + flag);
					}
					else{
						
						arrlangcheck.remove(buttonView.getText().toString());
						System.out.println("arrlangcheck.size()  " + arrlangcheck.size());
						flag--;
						System.out.println("flag =   " + flag);
					}
						
					
				}
			});
			lllistlang.addView(checkbox);
		}
		
		checkboxall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				CheckBox chk;
				if(isChecked)
				{
					
					for(int i=0;i<arrlistlanguage.size();i++)
					{
						chk =(CheckBox)lllistlang.getChildAt(i+1);
						chk.setChecked(true);
						//flag++;
					}
					System.out.println("flag =   " + flag);
					//checkbox.setChecked(true);
				}else{
					for(int i=0;i<arrlistlanguage.size();i++)
					{
						chk =(CheckBox)lllistlang.getChildAt(i+1);
						chk.setChecked(false);
						//flag--;
					}
					System.out.println("flag =   " + flag);
				}
				
			}
		});
		
		btnExport.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println(" isCheksync = " +isCheksync);
				
				if(isCheksync == true){
					if( TestNetworkConnection.getNetworkStatusNoDialog(getApplicationContext()) == true)
					{
						if(syncDocs.isAuthorize() == true){
							Exportdata();
						}
						else {
								showDialog(DIALOG_AUTHO);
						}
					System.out.println("sysDocs.isAuthorize(); = "+ syncDocs.isAuthorize());
					}
					else{
						Toast.makeText(getApplicationContext(), "Please check your connection ! ", Toast.LENGTH_SHORT).show();
					}
				}
				else {
					Exportdata();
				}
				//Exportdata();
			}
		});
		
		LoadSharePreferences();
		
		checkbox_Sync.setOnCheckedChangeListener(onCheck_Sync);
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		 AlertDialog.Builder dialog =new AlertDialog.Builder(this);
			switch (id) {
			
			case DIALOG_AUTHO:
				 LayoutInflater factory = LayoutInflater.from(this);
		            final View textEntryView = factory.inflate(R.layout.login_google, null);
		            dialog.setTitle("Login your account! ");
		            dialog.setView(textEntryView);
		            
		            dialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            			final EditText etEmail = (EditText) textEntryView.findViewById(R.id.editText_myEmail);
		                    	final EditText etPass = (EditText) textEntryView.findViewById(R.id.editText_myPass);
		                    	final CheckBox cbShowpass = (CheckBox)textEntryView.findViewById(R.id.checkBox_showpassword_login);
		                    	
		                    	String strEmail =  String.valueOf(etEmail.getText()).trim();
		                    	String strPass =  String.valueOf(etPass.getText()).trim();
		                    	
		                    	cbShowpass.setOnCheckedChangeListener(new  CompoundButton.OnCheckedChangeListener() {
									@Override
									public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
										System.out.println("isChecked show pass = "+isChecked );
										
										if (isChecked) {
											etPass.setInputType(InputType.TYPE_CLASS_TEXT);
										} else {
											etPass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
										}
									}
								});
		                    	
		                        // them catalog
		                    	if(strEmail != "" && strPass!=""){
		                    		if(strEmail.endsWith("@gmail.com")!=true)
		                    		{
		                    			strEmail = strEmail+"@gmail.com";
		                    			System.out.println("email = "+ strEmail);
		                    		}
		                    		try {
		                    			syncDocs.Autho(strEmail, strPass);
		                    			if(syncDocs.isAuthorize()==false)
		                    			{
		                    				dialogmessage = "Login fail ! ";
		                    				showDialog(DIALOG_RESULT_AUTHO);
		                    			}
		                    			else{
		                    				Toast.makeText(getApplicationContext(), "Login success ! ", Toast.LENGTH_SHORT).show();
		                    				showstatus.setVisibility(View.VISIBLE);
		                    				showstatus.setText("Login your account success. Click Play to export data to google.");
		                    			}
									} catch (Exception e) {
										dialogmessage = "Login fail ! ";
									}
		                    		
		                    		dialog.dismiss();
		                    	}
		                    	else{
		                    		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
		                    	}
		                    	
		                    }
		                });
		                dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int whichButton) {
		                        dialog.dismiss();
		                    }
		                });
		                AlertDialog alert0 = dialog.create();
		    			return alert0;
		           
			case DIALOG_RESULT_AUTHO:
				dialog.setTitle(" Notice! ");
				dialog.setMessage(dialogmessage);
				dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alertresult = dialog.create();
				return alertresult;
				
				
			 case DIALOG_WAITTING: {
	                ProgressDialog dialogwait = new ProgressDialog(this);
	                dialogwait.setMessage(dialogmessage);
	                dialogwait.setIndeterminate(true);
	                dialogwait.setCancelable(true);
	                //dialogwait.s
	               
	                return dialogwait;
	            }
			}
            return super.onCreateDialog(id);
	}
	
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		progress.setVisibility(View.GONE);
		showstatus.setVisibility(View.INVISIBLE);
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		ExportData.this.finish();
	}
 	private void writeFile(String path, ArrayList<String> data) {
		String[] temp = path.split("/");
		String fileName = temp[temp.length-1];
		String tempPath = path.replace(fileName, "");
		File file = new File(tempPath);
		
		long totalSize = data.size();
		long currentPos = 0;
		
		if(!file.exists()){
			if(file.mkdirs()){
				Log.e("cannc", "Success create path - " + path);
			}
			else{
				Log.e("cannc", "Error: Cann't create path - " + tempPath);
			}
		}
		if(file.exists()){
			try {
				Log.e("cannc", "Success Backup - " + path);
				FileWriter out = new FileWriter(path, false);
				
				for(int i = 0; i < data.size(); i++) {
					out.write(data.get(i));
					out.write("\n");
					
					// chay progress tai vi tri current
					currentPos =i;
					progress.setProgress((int)((currentPos*100)/totalSize));

					
				}
				
				out.close();
			}
			catch (IOException e)
			{
				Log.e("cannc", "Error: cann't write file backup - " + path);
			}
		}
	}
	
 	public void Exportdata(){
 		
 		filename = et_Enterfilename.getText().toString().trim();
 		
 		if (flag<1) {
 			dialogmessage = "Please check in language to export";
			showDialog(0);
		}
 		else
 		{
			if(filename.equals("")) {
				dialogmessage = "Please input file name";
				showDialog(0);
			}
			else{
				filepath = path + filename+".csv";
				//path = Environment.getExternalStorageDirectory() + projectname + inputPath+".csv";
				for(int i=0;i<arrlangcheck.size();i++){
					languageExport = arrlangcheck.get(i).toString();
					//data = wordData.getWordsToBackupByLanguage(languageExport);
					data.addAll(wordData.getWordsToBackupByLanguage(languageExport));
					System.out.println("languageExport   "+languageExport);
				}
				System.out.println("data.size()   "+data.size());
				new DoBackgroundImportFile().execute("abc");
			}
 		}
 		
 	}
	
 	
 	private android.widget.CompoundButton.OnCheckedChangeListener onCheck_Sync = new android.widget.CompoundButton.OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			isCheksync = isChecked;
			
		}
	};
 	
 	private void LoadSharePreferences(){
		SharedPreferences sharedPreferences = getSharedPreferences("InsertQuestion", MODE_PRIVATE);
		isCheksync = sharedPreferences.getBoolean(SettingActivity.SYNC, false);
		checkbox_Sync.setChecked(isCheksync);
	}

	 @Override
		protected Dialog onCreateDialog(int id) {
			// TODO Auto-generated method stub
			//return super.onCreateDialog(id);
			   AlertDialog.Builder dialog =new AlertDialog.Builder(this);
			switch (id) {
			
			case 0:
				dialog.setTitle(" Notice! ");
				dialog.setMessage(dialogmessage);
				dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				AlertDialog alert1 = dialog.create();
				alert1.show();
				break;
			}
			return null;
	   }//end dialog
	 

	 private class DoBackgroundImportFile extends AsyncTask<String, Integer, Long>{

		 
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				progress.setVisibility(View.VISIBLE);
				btnExport.setVisibility(View.INVISIBLE);
				progress.setProgress(myprogress);
				
				
				if(syncDocs.isAuthorize() == true && isCheksync == true)
				{
					showstatus.setVisibility(View.INVISIBLE);
					progress.setVisibility(View.INVISIBLE);
					dialogmessage = "Please wait while synchronizing...";
					showDialog(DIALOG_WAITTING);
				}
				else{
					
					showstatus.setVisibility(View.VISIBLE);
				}
				showstatus.setText("Loading...");
			}

			@Override
			protected void onPostExecute(Long result) {
				// TODO Auto-generated method stub
				Log.d("Import file","finished import");
				
				
				progress.setProgress(100);
				progress.setVisibility(View.GONE);
				btnExport.setVisibility(View.VISIBLE);
				
				data.clear();
				
				if(syncDocs.isAuthorize() == true && isCheksync == true)
				{
					
					AsyncTask<String, String, String> downloadFile = new AsyncTask<String, String, String>(){

						@Override
						protected void onPreExecute() {
							// TODO Auto-generated method stub
							super.onPreExecute();
						}

						@Override
						protected void onPostExecute(String result) {
							// TODO Auto-generated method stub
							super.onPostExecute(result);
							dismissDialog(DIALOG_WAITTING);
							showstatus.setText(" Export successful! ");
						}

						@Override
						protected String doInBackground(String... params) {
							try {
								// start to update data to google doc
								syncDocs.UpdateToGoogleDocs(new File(filepath), filename);
								showstatus.setVisibility(View.VISIBLE);
							} catch (Exception e) {
							}
							return "";

						}
						
					}.execute("");
				}
				else{
					showstatus.setText(" Export successful! ");
				}
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				Log.d("ANDRp_ASYN",""+values[0]);
				progress.setProgress(values[0]);
			}

			@Override
			protected Long doInBackground(String... params) {
				// TODO Auto-generated method stub
				try {
					writeFile(filepath, data);
				} catch (Exception e) {
					System.out.println(e);
				}
				return null;
			}


		}
	 
	 private static final String RELOGIN = "Login with another account";
		
	   @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// TODO Auto-generated method stub
			super.onCreateOptionsMenu(menu);
			CreateMenu(menu);
			return true;
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// TODO Auto-generated method stub
			super.onOptionsItemSelected(item);
			return MenuChoice(item);
		}

		private void CreateMenu(Menu menu)
	    {
	    	menu.add(0, 0, 0, RELOGIN);
	    }
		
	   private boolean MenuChoice(MenuItem item)
	   {
		switch (item.getItemId()) {
		case 0:
			showDialog(DIALOG_AUTHO);
			return true;
		}
		return false;
		   
	   }   

	
	 

}
